﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php
using System;
using System.Collections.Generic;
using DNA.Utility;

namespace DNA.Mvc
{
    public class WidgetTemplateBuilder
    {
        private WidgetTemplate tmpl;

        public WidgetTemplate GetTemplate()
        {
            return tmpl;
        }

        public WidgetTemplateBuilder From(string xml)
        {
            if (string.IsNullOrEmpty(xml)) throw new ArgumentNullException("xml");
            tmpl = XmlSerializerUtility.DeserializeFromXmlText<WidgetTemplate>(xml);
            return this;
        }

        public WidgetTemplateBuilder From(WidgetInstance widget, string installedPath)
        {
            if (widget.IsStatic)
                throw new FormatException("The static widget can not generate template");

            if (widget.WidgetDescriptor == null)
                throw new ArgumentNullException("widget.WidgetDescriptor");

            string path = installedPath + (installedPath.EndsWith("\\") ? "" : "\\") + widget.WidgetDescriptor.InstalledPath + "\\config.xml";

            var tmpl = XmlSerializerUtility.DeserializeFormXmlFile<WidgetTemplate>(installedPath);

            tmpl.Defaults = new WidgetDefaults()
            {
                Title = widget.Title,
                TitleLinkUrl = widget.TitleLinkUrl,
                IconUrl = widget.IconUrl,
                ShowBorder = widget.ShowBorder,
                ShowHeader = widget.ShowHeader,
                HeaderCssText = widget.HeaderCssText,
                CssText = widget.CssText,
                BodyCssText = widget.BodyCssText,
                Action = widget.WidgetDescriptor.Action,
                ZoneID = widget.ZoneID,
                Position = widget.Pos,
                Controller = widget.WidgetDescriptor.Controller,
                Area = widget.WidgetDescriptor.Area
            };

            tmpl.ID = widget.ID.ToString();

            var _preferences = widget.ReadUserPreferences();
            tmpl.UserPreferences = new List<WidgetUserPreference>();
            foreach (var key in _preferences.Keys)
            {
                tmpl.UserPreferences.Add(new WidgetUserPreference()
                {
                    Type = _preferences[key].GetType().ToString(),
                    Name = key,
                    Value = _preferences[key].ToString()
                });
            }
            return this;
        }

        public WidgetTemplateBuilder From(SimpleWidgetModel widget)
        {
            //string widgetPath = installedPath + (installedPath.EndsWith("\\") ? "" : "\\") + widget.Name + "\\";
            var tmpl = new WidgetTemplate()
            {
                Name = widget.Name,
                Version = "1.0",
                Description = widget.Description
            };

            if (widget.ContentType.Equals("html"))
            {
                tmpl.Content.ContentType = "text/html";
                if (!string.IsNullOrEmpty(widget.ContentText))
                    tmpl.Content.Text = widget.ContentText;
            }
            else
            {
                tmpl.Content.Source = "index." + widget.ContentType;
            }

            return this;
        }

        public WidgetTemplateBuilder SetID(string id) { tmpl.ID = id; return this; }

        public WidgetTemplateBuilder SetName(string name) { tmpl.Name = name; return this; }

        public WidgetTemplateBuilder SetVerion(string version) { tmpl.Version = version; return this; }

        public WidgetTemplateBuilder SetDesc(string desc) { tmpl.Description = desc; return this; }

        public WidgetTemplateBuilder SetTitle(string title) { tmpl.Defaults.Title = title; return this; }

        public WidgetTemplateBuilder SetTitleLink(string url) { tmpl.Defaults.TitleLinkUrl = url; return this; }

        public WidgetTemplateBuilder SetIcon(string url) { tmpl.Defaults.IconUrl = url; return this; }

        public WidgetTemplateBuilder SetShowBorder(bool value) { tmpl.Defaults.ShowBorder = value; return this; }

        public WidgetTemplateBuilder SetShowHeader(bool value) { tmpl.Defaults.ShowHeader = value; return this; }

        public WidgetTemplateBuilder SetZoneID(string zoneID) { tmpl.Defaults.ZoneID = zoneID; return this; }

        public WidgetTemplateBuilder SetPos(int pos) { tmpl.Defaults.Position = pos; return this; }

        public WidgetTemplateBuilder SetHeaderCssText(string csstext) { tmpl.Defaults.HeaderCssText = csstext; return this; }

        public WidgetTemplateBuilder SetCssText(string csstext) { tmpl.Defaults.CssText = csstext; return this; }

        public WidgetTemplateBuilder SetBodyCssText(string csstext) { tmpl.Defaults.BodyCssText = csstext; return this; }

        public WidgetTemplateBuilder SetArea(string area) { tmpl.Defaults.Area = area; return this; }

        public WidgetTemplateBuilder SetAction(string action) { tmpl.Defaults.Action = action; return this; }

        public WidgetTemplateBuilder SetController(string ctrl) { tmpl.Defaults.Controller = ctrl; return this; }

        public WidgetTemplateBuilder SetFeature(string url, bool isRequired = false, object paramValues = null)
        {
            tmpl.Feature = new WidgetFeature() { Url = url, IsRequried = isRequired };

            if (paramValues != null)
            {
                tmpl.Feature.Params = new List<WidgetFeatureParam>();

                var _params = ObjectHelper.ConvertObjectToDictionary(paramValues);
                foreach (var key in _params.Keys)
                    tmpl.Feature.Params.Add(new WidgetFeatureParam() { Name = key, Value = _params[key].ToString() });
            }

            return this;
        }

        public WidgetTemplateBuilder SetAuthor(string name, string email = "", string url = "")
        {
            tmpl.Author.Name = name;
            if (!string.IsNullOrEmpty(email)) tmpl.Author.Email = email;
            if (!string.IsNullOrEmpty(url)) tmpl.Author.Uri = url;
            return this;
        }

        public WidgetTemplateBuilder SetContentUrl(string url)
        {
           // if (tmpl.Content == null) tmpl.Content = new WidgetContent();
            tmpl.Content.Source = url;
            return this;
        }

        public WidgetTemplateBuilder SetContentType(string type)
        {
            tmpl.Content.ContentType = type;
            return this;
        }

        public WidgetTemplateBuilder SetContentText(string text)
        {
            tmpl.Content.Text = text;
            return this;
        }

        public WidgetTemplateBuilder AddIcon(string url, int width = 16, int height = 16)
        {
            if (tmpl.Icons == null) tmpl.Icons = new List<WidgetIcon>();

            tmpl.Icons.Add(new WidgetIcon() { Source = url, Width = width, Height = height });
            return this;
        }

        public WidgetTemplateBuilder AddLicense(string source, string text = "")
        {
            if (tmpl.Licenses == null) tmpl.Licenses = new List<WidgetLicense>();
            tmpl.Licenses.Add(new WidgetLicense() { Source = source, Text = text });
            return this;
        }

        public WidgetTemplateBuilder AddUserPreference<T>(string name, T value, bool isReadOnly = false)
        {
            if (tmpl.UserPreferences == null) tmpl.UserPreferences = new List<WidgetUserPreference>();
            tmpl.UserPreferences.Add(new WidgetUserPreference() { Name = name, Value = value.ToString(), IsReadonly = isReadOnly });
            return this;
        }

        public string GetXml()
        {
            if (tmpl == null) throw new ArgumentNullException();
            return XmlSerializerUtility.SerializeToXml(GetTemplate());
        }
    }
}
